package com.alibaba.middleware.hsf.guide.server.service;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.FactoryBean;

public class ServiceProxy implements InvocationHandler, FactoryBean {
    private static Set<Method> methods = new HashSet<Method>(Arrays.asList(Object.class.getDeclaredMethods()));
    private Object proxy;
    private Object src;
                   
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (methods.contains(method)) {
            return method.invoke(src, args);
        }
        
        System.out.println(method + " invoked.");
        
        return method.invoke(src, args);
    }
    
    @Override
    public Object getObject() throws Exception {
        return proxy;
    }
    
    @Override
    public Class<?> getObjectType() {
        if (src == null) {
            return null;
        }
        return src.getClass();
    }
    
    @Override
    public boolean isSingleton() {
        return true;
    }
    
    public void setSrc(Object src) {
        this.src = src;
        this.proxy = Proxy.newProxyInstance(src.getClass().getClassLoader(), src.getClass().getInterfaces(), this);
    }
    
}
